package com.siboxuetang.need.web.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import com.siboxuetang.need.util.WebUtils;
import com.siboxuetang.need.vo.NeedException;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

public class NeedExceptionResolver implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        NeedException exception = null;
        if(e instanceof NeedException){
            exception = (NeedException) e;
        }else {
            exception = new NeedException(498, e.getMessage());
        }
        //方便调试
        e.printStackTrace();
        if(WebUtils.isAjaxRequest(httpServletRequest)){
            return excuteApiRequest(httpServletRequest, httpServletResponse, exception);
        }else{
            return excutePageRequest(httpServletRequest, httpServletResponse, exception);
        }
    }

    private ModelAndView excuteApiRequest(HttpServletRequest req, HttpServletResponse resp, NeedException e){
        FastJsonJsonView jsonView = new FastJsonJsonView();
        Map<String,Object> maps = new HashMap<>();
        maps.put("status", e.getStatus());
        maps.put("error", e.getErrorMaps());
        maps.put("msg",e.getMessage());
        jsonView.setAttributesMap(maps);
        return new ModelAndView(jsonView);
    }

    private ModelAndView excutePageRequest(HttpServletRequest req, HttpServletResponse resp, NeedException e){
        ModelAndView mv = new ModelAndView();
        mv.setStatus(HttpStatus.INTERNAL_SERVER_ERROR);
        mv.setViewName("error");
        mv.addObject(e);
        return mv;

    }

}
